package com.tiankun.eurekaticket.controller;


import com.tiankun.eurekaticket.exception.BusinessException;
import com.tiankun.eurekaticket.util.JsonResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @Author liaopeng
 * @Date 2020/10/24 10:45
 * @Version 1.0
 **/
@RestController
@RequestMapping("/ticketimg")
public class UploadController {

    @RequestMapping("/upload")
    public Map upload(@RequestParam("file") MultipartFile file){

        JsonResult jsonResult = new JsonResult();
        if (file.isEmpty()){
            throw new BusinessException("文件不能为空");
        }
        //判断文件大小是否符合要求（不能超过1M）
        if (file.getSize()>1024*1024){
            throw new BusinessException("文件不能大于1M");
        }
        //获取上传文件的原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取上传文件的后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //String substring = originalFilename.substring(originalFilename.lastIndexOf("." + 1));
        //后缀必须是：PNG/jpg/jpge/gif
        //判断上传文件的后缀名是否符合规范
        if (substring.trim().equals("png")||substring.trim().equals("jpg")||substring.trim().equals("jpeg")||substring.trim().equals("gif")){
        //通过UUID生成文件名+原来的后缀=组成新的文件名
            //将上传文件的文件名替换，显示虚拟的文件
            String newFileName= UUID.randomUUID().toString().replace("-","")+"."+substring;
            //真实的文件路径
            //1.保存在Windows本地文件夹
            //String newFileName2 ="D:\\img\\" + newFileName;
            //2.保存在阿里云服务器Linux系统文件夹中
            String newFileName2="/usr/upload/img/"+newFileName;
            //保存文件
            File uploadFile = new File(newFileName2);
            try {
                file.transferTo(uploadFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //返回给前端
            jsonResult.put("file","http://106.14.39.205:8770/tiankun-api-ticket/img/"+newFileName);
            jsonResult.setCode("1");
            jsonResult.setMsg("图片上传成功");
        }
        return jsonResult.getValues();
    }
}
